package com.wny.activities;

import com.wny.R;
import com.wny.backend.FormattedDisplay;
import com.wny.backend.LocalListStorage;
import com.wny.backend.SocketsClient;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DisplayListActivity extends ListActivity implements LocationListener {

	LayoutInflater mInflater;
	LocalListStorage theLists;
	SocketsClient socket;
	String request;
	String requestType;
	LocationManager myProvider;
	int uid;
	int eid;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myProvider = (LocationManager) getSystemService(LOCATION_SERVICE);
		theLists = new LocalListStorage();
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		setContentView(R.layout.thelistdisplay);
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			request = extras.getString("request");
			requestType = extras.getString("requestType");
			uid = extras.getInt("uid");
			eid = extras.getInt("eid");
		}

	}
	public boolean onCreateOptionsMenu(Menu menu) {
		// super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		//if (requestType == "myEvents")
			inflater.inflate(R.menu.event_menu, menu);
		return true;

	}
	public boolean didUserJoinEventAlready(int event_id) throws IOException
	{
		char[] result=null;
		SocketsClient myComm = SocketsClient.getSocket();
		String is_user_in_event;
		result = myComm.sendData(("get=eventList&uid="+uid+"&eid="+event_id+"\n").getBytes());
		is_user_in_event=String.valueOf(result);
	
		
		if ( Character.isDigit(is_user_in_event.charAt(0)) ){
			
			return true;
		}
		else{
			
			return false;
		}
		
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.create_event:
			Intent createEventIntent = new Intent(DisplayListActivity.this,
					CreateEventActivity.class);
			setTitle("Create Event");
			createEventIntent.putExtra("uid", uid);
			startActivity(createEventIntent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	// populates the ArrayList that holds the data for our events and users.
	// Data is further organized with FormattedDisplay class
	private void populateList(ArrayList<FormattedDisplay> toDisplay) {
		CustomAdapter myListDrawer = new CustomAdapter(this, R.layout.list,
				R.id.title, toDisplay);
		setListAdapter(myListDrawer);
		getListView().setTextFilterEnabled(true);
	}

	// used to create the list view of our events and users
	private class CustomAdapter extends ArrayAdapter<FormattedDisplay> {

		public CustomAdapter(Context context, int resource,
				int textViewResourceId, List<FormattedDisplay> objects) {
			super(context, resource, textViewResourceId, objects);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			TextView title = null;
			TextView detail = null;
			ImageView i11 = null;
			// calls Formatted Display constructor. The getItem pulls the data
			// from the corresponding place
			// on the list. The user selects this value onClick

			FormattedDisplay myFormattedDisplayObject = getItem(position);
			String[] displayStrings = myFormattedDisplayObject.displayStrings();
			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.list, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}
			// sets the title, image, and detail information for object in list
			holder = (ViewHolder) convertView.getTag();
			title = holder.gettitle();
			title.setText(displayStrings[0]);
			detail = holder.getdetail();
			detail.setText(displayStrings[1]);
			i11 = holder.getImage();
			i11.setImageResource(R.drawable.ic_launcher);
			return convertView;
		}

		/**
		 * The Class ViewHolder.
		 */
		private class ViewHolder {

			private View mRow;
			private TextView title = null;
			private TextView detail = null;
			private ImageView i11 = null;

			public ViewHolder(View row) {
				mRow = row;
			}

			public TextView gettitle() {
				if (null == title) {
					title = (TextView) mRow.findViewById(R.id.title);
				}
				return title;
			}

			public TextView getdetail() {
				if (null == detail) {
					detail = (TextView) mRow.findViewById(R.id.detail);
				}
				return detail;
			}

			public ImageView getImage() {
				if (null == i11) {
					i11 = (ImageView) mRow.findViewById(R.id.img);
				}
				return i11;
			}
		}
	}

	// the Restart,onResume,Pause, and Stop functions deals with loopback with
	// Android emulator
	// loopback for Anroid emulator is 10.0.2.2 (not 127.0.0.1!)

	protected void onStart() {
		super.onStart();
		try {
			socket = SocketsClient.getSocket();
			if(requestType.equals("user"))
			{
			char[] listOfUsers = socket.sendData(request.getBytes());
			theLists.setUserList(listOfUsers);
			populateList(theLists.getUserList());
			}
			else
			{
				char[] listOfEvents = socket.sendData(request.getBytes());
				theLists.setEventList(listOfEvents);
				populateList(theLists.getEventList());
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public boolean isUserFriend(int friend_uid) throws IOException {

		char [] get_friend_info;
		String friend_info;
		SocketsClient myComm = SocketsClient.getSocket();
		get_friend_info=myComm.sendData(("get=friend&uid1="+uid +"&uid2="+friend_uid+"\n").getBytes());

		friend_info=String.valueOf(get_friend_info);	

		//if the UID is returned, it means the users are friends
		if( (String.valueOf(friend_info.charAt(0)).equals(String.valueOf(uid))) ){
			return true;
		}
		//otherwise return false
		return false;

	}
	public void onListItemClick(ListView parent, View v, int position,long id) {  
		FormattedDisplay disp = (FormattedDisplay)parent.getItemAtPosition(position);
		boolean isJoined;
		int otherUid=disp.userID();
		//user not event
		if(disp.userID()!=-1) {
			try {
				boolean is_friend=isUserFriend(disp.userID());

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Intent displayUserIntent = new Intent(DisplayListActivity.this, UserActivity.class);
			displayUserIntent.putExtra("uid", uid);
			displayUserIntent.putExtra("otherUid", otherUid);
			try {
				displayUserIntent.putExtra("friends", isUserFriend(otherUid));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			startActivity(displayUserIntent);
		}
		else
		{
			int eid = disp.eventID();
			try
			{
				isJoined = didUserJoinEventAlready(eid);
				Intent displayEventIntent = new Intent(DisplayListActivity.this, EventActivity.class);
				displayEventIntent.putExtra("uid", uid);
				displayEventIntent.putExtra("eid", eid);
				displayEventIntent.putExtra("joined", isJoined);
				startActivity(displayEventIntent);
			}
			catch (Exception e) {
				// TODO: handle exception
			}	
		}
	}

	protected void onResume() {
		super.onResume();
		socket = SocketsClient.getSocket();
		myProvider.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, this);

	}

	protected void onPause()
	{
		myProvider.removeUpdates(this);
		super.onPause();
	}

	protected void onStop() {
		super.onStop();
	}
	// a wrapper function for the Toast class. Used to show messages onscreen
	private void displayWithToast(String toShow, int duration) {
		Toast temp = Toast.makeText(this, toShow, duration);
		temp.setGravity(Gravity.CENTER, 0, 0);
		temp.show();
	}
	public void onLocationChanged(Location location)
	{
		// TODO Auto-generated method stub
		
		SocketsClient myComm = SocketsClient.getSocket();
		try {
			myComm.sendNonblocking(("loc&"+location.getLatitude()+"&"+location.getLongitude()+"&"+this.uid+"\n").getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	

	//notifies user GPS disables
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		displayWithToast("The system GPS service has been disabled.", 5000);
	}

	//notifies user GPS enabled
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		displayWithToast("GPS is now avaliable", 4000);

	}

	//notifies user of any change in the status of the GPS
	public void onStatusChanged(String location_provider, int status, Bundle otherVariables) {
		// TODO Auto-generated method stub
		switch (status)
		{
		case LocationProvider.OUT_OF_SERVICE:
			displayWithToast("The GPS is out of service.", 5000);
		case LocationProvider.TEMPORARILY_UNAVAILABLE:
			displayWithToast("The GPS is temporarially unavaliable", 5000);
		case LocationProvider.AVAILABLE:
			displayWithToast("GPS is now avaliable", 5000);
		}

	}

}
